if (typeof jQuery === 'undefined') { throw new Error('CSStrat\'s JavaScript requires jQuery') }

//ON utilise ici les fonctions qu'on a besoin pour faire fonctionner notre démo


// VARIABLES GLOBALES
var i = 1;
var selectedPlayer = "";
var px = -1;
var py = -1;

// PAPER.JS 
var canvas = undefined;
var lastPos = undefined;
var curPos = undefined;
var colors = new Array("red", "blue", "olivedrab", "teal", "plum");

// FIN VARIABLES

/**
 * Objet representant un waypoint.
**/
function Waypoint(playerId, previous, x, y, action)
{
	this.playerId = playerId;
	this.previous = previous;
	this.x = x;
	this.y = y;
	this.action = action;
}

// Array de waypoints
var waypoints = new Array();

function selectPlayer(id) {
    console.log("Selected " + id);
    selectedPlayer = id;
}

/*
 Lors d'un click sur la carte, va generer les boutons pour les options pour cet endroit
 */
function editStrategy(event, o) {
  if (event.target != '[object HTMLButtonElement]') {
    // Box
    xBox = event.clientX - o.getBoundingClientRect().left;
    yBox = event.clientY - o.getBoundingClientRect().top;
    stratBox( xBox, yBox );

  }
}

function initCanvas() {
  if ( canvas == undefined ) {
    canvas = document.getElementById('myCanvas');
    paper.setup(canvas);
  }
}


/**
 * Boîte avec les boutons de choix de "waypoint" pour la stratégie.
*/
function stratBox( x, y )
{
	if (selectedPlayer !== "")
	{	
	  var box = document.getElementById('choicesbox');
	  box.style.left = x + 'px';
	  box.style.top = y + 'px';
	  px = x;
	  py = y;
	  lastPos = curPos;
	  curPos = new paper.Point( x, y );
	  box.innerHTML = '<div>' +
						'<div><button type="submit" class="btn btn-success" onclick="addWaypoint(1)" style="width:120px;">Bouger</button></div>' +
						'<div><button type="submit" class="btn btn-success" onclick="addWaypoint(2)" style="width:120px;">Grenade</button></div>' +
						'<div><button type="submit" class="btn btn-success" onclick="addWaypoint(3)" style="width:120px;">Armer bombe</button></div>' +
					  '</div>';
	}
	else
	{
		$('#warningBox').html('<div class="alert alert-warning alert-dismissable voffset2" onclick=hideWarning()>Veuillez choisir un joueur!</div>');
		$('#warningBox').show();
	}
}

// Cache un avertissement.
function hideWarning()
{
	$('#warningBox').hide();
}

/*
 Rajoute le waypoint sur la carte pour le joueur selectionne
 */
function addWaypoint(option)
{
	if ( selectedPlayer !== "" )
	{
		var o = new Waypoint(selectedPlayer, "", px, py, option);
		
		for (var w in waypoints)
		{
			if(waypoints[w].playerId === selectedPlayer)
			{
				console.log("Found");
				o.previous = waypoints[w];
			}
		}
		waypoints.push(o);
		drawWayPoint(new paper.Point(px, py), option);
		
		var prev = o.previous;
		if (prev !== "")
		{
			console.log(prev.action);
			while (prev !== "" && prev.action === 2) {
				console.log("grenade detected");
				prev = prev.previous;
			}
			drawLine(new paper.Point(px, py), new paper.Point(prev.x, prev.y));
		}
	}
	else 
	{
		console.log("Faut choisir un joueur");
		$('#warningBox').css("visibility", "visible");
		$('#warningBox').html("Il faut choisir un joueur!");
	}
	
	$('#choicesbox').html('');
	px = -1;
	py = -1;
}


function btnAddPlayer() {
  var newId = findLowestFreeId();

    if ($('#newPlayerName').val() !== "" && i < 6) {
      initCanvas();
      var newA = '<a href="#" name="player' + newId + '" class=\'list-group-item\' id='+ $('#newPlayerName').val()+newId + ' onclick="selectPlayer('+ newId +')">'
                    + '<b style="color: ' + colors[newId-1] + '">' + $('#newPlayerName').val() + '</b>'
                    + '<button class="glyphicon glyphicon-remove pull-right" onclick="removePlayer('+ newId +');"></button>'
                  +'</a>';
      $('#playerList').append(newA);
      $('#playerList a:last-child').click(function() {
        $('#playerList a').each(function() {
          $(this).attr('class','list-group-item');
        });
        $(this).attr('class','list-group-item active');
      });
      $('#newPlayerName').val('');
      i++;
    }
}

/**
 * from et to doivent être des objets paper.Point 
*/
function drawLine( from, to ) {
  if ( canvas ) {
    // Create a Paper.js Path to draw a line into it:
    var path = new paper.Path();
    // Give the stroke a color
    path.strokeColor = colors[selectedPlayer-1];
    var start = new paper.Point(100, 100);
    // Move to start and draw a line from there
    path.moveTo( from );
    // Note that the plus operator on Point objects does not work
    // in JavaScript. Instead, we need to call the add() function:
    path.lineTo( to );
    // Draw the view now:
    paper.view.draw();
  }
}

/*
 * pos doit être un objet paper.Point
 */
function drawWayPoint( pos, option ) {
	initCanvas();

	switch (option) {
	case 1: // mouvement joueur
		var waypoint = new paper.Path.Circle({
			center: pos,
			radius: 4,
			fillColor: colors[selectedPlayer-1]
		});
		break;
	case 2: // lancer une grenade
		var p = new paper.Point(pos.x-4, pos.y-4);
		var waypoint = new paper.Path.Rectangle({
			point: p,
			size: [8, 8],
			fillColor: "#cacaca",
      strokeColor: "black"
		});
		break;
	case 3: // armer une bombe
		var waypoint = new paper.Path.RegularPolygon({
			center: pos,
			sides: 3,
			radius: 8,
			fillColor: "orange",
      strokeColor: "black"
		});
		break;
	}
  /*
  if ( lastPos && curPos ) {
    var path = new paper.Path();
    path.strokeColor = "purple";
    path.moveTo( lastPos );
    path.lineTo( curPos );

  }
	*/
	paper.view.draw();
}

// Fonction le bouton de creation la strategie
function create() {
    var name = "";
    if (chosenMap !== "")
    {
        name = $('#strategyName').val();

        if (name != "")
        {
            // Aller a la page d'elaboration
            window.location = "createEditStrat.php?name=" + name + "&map=" + chosenMap;
        }
        else
        {
            window.location = "create.php?msg=noname";
        }
    }
    else  {
        window.location = "create.php?msg=nomap";
    }
}

/*
 * Trouve le plus petit "id" de joueur qui est libre (si on a enlevé un joueur)
*/
function findLowestFreeId() {
  var pId = 0;
  var j = 1;
  while( pId==0 ) {
    if ( ! $("#playerList > a[name='player" + j + "']").length ) {
      pId = j;
    } else {
      j++;
    }
  }

  return pId;
}

/**
 * Enlève un joueur de la liste par son ID.
*/
function removePlayer( id ) {
  $("a[name='player" +id+ "']").remove();
  
  if ( selectedPlayer == id ) {
    selectedPlayer = "";
  }

  i--;
}

// Load les joueurs dynamiquement
function loadPlayers(){
      var playerOne = '<a href="#" name="player1" class="list-group-item">Simon B.</a>';
      var playerTwo = '<a href="#" name="player2" class="list-group-item">Simon L.</a>';
      var playerThree = '<a href="#" name="player3" class="list-group-item">Dominique</a>';
        
      $('#playerListView').append(playerOne);
      $('#playerListView').append(playerTwo);
      $('#playerListView').append(playerThree);

      $('#myCanvas').toggleClass('hidden');
}

function showMessage( msgId, msgText, msgType ) {
  if ( $('#' + msgId).length == 0 ) {
    var msg = '<div id="' + msgId + '" class="alert alert-'+ msgType +'">'
                  + msgText
              + '</div>';
    $('#main_container').prepend( msg );
  }
}
